﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;

using FRL.DebtChased.Repository;
using FRL.DebtChased.Repository.ViewModels;
using FRL.DebtChased.Website;

namespace WebApplication.Finance
{

	/// <summary>
	/// Declaration of AuditTrail
	/// </summary>
	public partial class AuditTrail : System.Web.UI.Page
	{

		/////////////////////////////////////////////////////////////
		// Attributes

		private bool m_bRebind = false;

		/////////////////////////////////////////////////////////////
		// Event handlers

		protected override void OnPreRender(EventArgs e)
		{

			// Call base-class function
			base.OnPreRender(e);

			// If rebinding...
			if (m_bRebind)
			{

				// Get the search string
				string strSearch = null;
				if(txtSearch.Text.Length > 0)
				{
					if( (txtSearch.Text.StartsWith("%")) || (txtSearch.Text.EndsWith("%")) )
						strSearch = txtSearch.Text;
					else
						strSearch = string.Format("%{0}%",txtSearch.Text);
				}

				// Get the user filter
				int iUserId = 0;
				MySession mySession = MySession.BindMySession();
				if (mySession.ContainsRole(Definitions.eRoles.FIN_SYSADMIN))
					iUserId = 0;
				else
					iUserId = mySession.UserID;

				// Load the audit-trail
				AuditModel m = null;
				using (DebtChasedEntities ent = new DebtChasedEntities())
				{
					m = new AuditModel(ent,strSearch,0);
				}

				// Load the grid
				gridResult.DataSource = m.Elements;
				gridResult.DataBind();

			}

		}

		protected void Page_Load(object sender, EventArgs e)
		{

			// If this is a postback...
			if (this.IsPostBack)
			{

			}
			else
			{

				// Rebind the grid
				m_bRebind = true;

				// Set panel colours
				MyApplication myApp = MyApplication.BindMyApplication();
				pnlParams.BackColor = myApp.PrimaryWebColor;
				pnlResults.BackColor = myApp.PrimaryWebColor;

			}

		}

		protected void butSearch_Click(object sender, EventArgs e)
		{

			// Validate the contact
			this.Validate();
			if (!this.IsValid)
				return;

			// Check the search string
			string strSearch = txtSearch.Text;
			if (strSearch.Length < 4)
				(this.Master as FinanceMaster).ErrorMessage = "Search string must be at least 4 characters";
			else
				m_bRebind = true;

		}

		protected void gridResult_RowDataBound(object sender, GridViewRowEventArgs e)
		{

			// If this is a data-row...
			if (e.Row.RowType == DataControlRowType.DataRow)
			{

				// Get the list of actions
				AuditModel.Element el = e.Row.DataItem as AuditModel.Element;

				// Get the grid and bind
				GridView gridActions = e.Row.FindControl("gridActions") as GridView;
				gridActions.DataSource = el.Children;
				gridActions.DataBind();

			}

		}

	}

}